package com.shiyi.sqlSession;

import com.shiyi.pojo.Configration;
import com.shiyi.pojo.MappedStatement;
import com.shiyi.util.GenericTokenParser;
import com.shiyi.util.ParameterMapping;
import com.shiyi.util.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Descrption
 * @Author: 十一
 * @Date: 2020/11/9 15:03
 * @Version V5.0
 **/
public class SimpleExcutor implements Excutor {

    @Override
    public <T> List<T> query(Configration configration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        BoundSql boundSql = getBoundSql(mappedStatement);
        Connection connection = configration.getDataSource().getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String parameterType = mappedStatement.getParameterType();
        Class<?> clazz = Class.forName(parameterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            // 反射获取到parameter的值
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            Field field = clazz.getDeclaredField(parameterMapping.getContent());
            field.setAccessible(true);
            Object param = field.get(params[0]);
            preparedStatement.setObject(i+1,param);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultClazz = Class.forName(resultType);
        // 使用内省将结果集进行封装
        List<Object> list = new ArrayList<>();
        while(resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object resultObj = resultClazz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClazz);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(resultObj,value);
            }
            list.add(resultObj);
        }
        connection.close();
        return (List<T>) list;
    }

    @Override
    public <T> T insert(Configration configration, MappedStatement mappedStatement, Object... params) throws ClassNotFoundException, SQLException, NoSuchFieldException, IllegalAccessException {
        return baseExcute(configration, mappedStatement, params[0]);
    }

    private <T> T baseExcute(Configration configration, MappedStatement mappedStatement, Object param1) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        BoundSql boundSql = getBoundSql(mappedStatement);
        Connection connection = configration.getDataSource().getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String parameterType = mappedStatement.getParameterType();
        Class<?> clazz = Class.forName(parameterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            // 反射获取到parameter的值
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            Field field = clazz.getDeclaredField(parameterMapping.getContent());
            field.setAccessible(true);
            Object param = field.get(param1);
            preparedStatement.setObject(i+1,param);
        }
        Integer result = preparedStatement.executeUpdate();
        return (T) result;
    }

    @Override
    public <T> T update(Configration configration, MappedStatement mappedStatement, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        return baseExcute(configration, mappedStatement, params[0]);
    }

    @Override
    public <T> T delete(Configration configration, MappedStatement mappedStatement, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        BoundSql boundSql = getBoundSql(mappedStatement);
        Connection connection = configration.getDataSource().getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        Boolean result = preparedStatement.execute();
        return (T) result;
    }

    /**
     *功能描述 解析自定义的SQL语句，将其中的#{}标记使用JDBC原生的？展位符
     * @author 十一
     * @date 2020/11/9 15:25
     */
    private BoundSql getBoundSql(MappedStatement mappedStatement) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String sql = parser.parse(mappedStatement.getSql());
        // 获取到原生sql中占位的参数列表，可用于后期通过反射替换
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(sql, parameterMappings);
    }
}
